package com.example.demo;

import com.example.entity.Student;

import com.example.server.StudentRepository;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by Administrator on 2018-2-6.
 */
@RestController
public class StudentController {

    @Autowired
    private StudentRepository studentRepository;




    /**
     * 查询学生列表
     * @return
     */
    @GetMapping(value = "/students")
    public List<Student> getStudentList(){
       return studentRepository.findAll();
    }

    /**
     * 添加学生
     * @param name
     * @param age
     * @return
     */
    @PostMapping(value = "/addStudent")
    public Student addStudent( @RequestParam("name") String name, @RequestParam("age") Integer age){
        Student student = new Student();

        student.setAge( age);
        student.setName( name);

        return studentRepository.save( student);
    }

    /**
     * 根据ID查询学生
     * @param id
     * @return
     */
    @GetMapping(value = "findStudent/{id}")
    public Student findById(@PathVariable("id") Integer id){
        return studentRepository.findOne(id);
    }

    /**
     * 根据ID更新student记录
     * @param id
     * @param name
     * @param age
     * @return
     */
    @PutMapping(value = "/student/{id}")
    public Student updateStudent(@PathVariable("id") Integer id, @RequestParam("name") String name, @RequestParam("age") Integer age){
        Student student = new Student();

        student.setId( id);
        student.setName( name);
        student.setAge( age);

        return studentRepository.save( student);
    }

    /**
     * 根据ID删除记录
     * @param id
     */
    @DeleteMapping(value = "student/{id}")
    public void deleteStudent(@PathVariable("id") Integer id){
        studentRepository.delete(id);
    }

    /**
     * 扩展,按年龄查询记录
     * @param age
     * @return
     */
    @GetMapping(value = "/findByAge")
    public List<Student > findByAge(@RequestParam("age") Integer age){
        return studentRepository.findByAge( age);
    }

}
